package test6;

import org.springframework.aop.framework.Advised;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * @author: mornd
 * @dateTime: 2023/5/11 - 21:33
 * Spring 代理的特点
 */

@SpringBootApplication
public class App {
    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
        Bean1 proxy = context.getBean(Bean1.class);
        //System.out.println(proxy.getClass());

        show(proxy);

        proxy.setBean2(new Bean2());
        System.out.println(proxy.getBean2());

        show(proxy);
        //System.in.read();

        context.close();
    }

    /*
        代理对象与目标对象的成员变量并不关联，只有代理类调用方法，让代理方法再执行目标方法返回目标的方法返回值，
        这样看上去目标与代理的变量就一致了
     */
    private static void show(Bean1 proxy) throws Exception {
        System.out.println("代理的成员变量：");
        System.out.println("flag---->" + proxy.flag);
        System.out.println("bean2--->" + proxy.bean2);
        System.out.println("flag---->" + proxy.isFlag());
        System.out.println("bean2--->" + proxy.getBean2());

        if(proxy instanceof Advised) {
            Advised adv = (Advised) proxy;
            Bean1 bean1 = (Bean1) adv.getTargetSource().getTarget();
            System.out.println("目标的成员变量：");
            System.out.println("flag---->" + bean1.flag);
            System.out.println("bean2--->" + bean1.bean2);
        }
    }
}
